package com.xuanzheng.company.service.impl;

import com.xuanzheng.company.dao.CompanyDao;
import com.xuanzheng.company.dao.CompanyEmployeeDao;
import com.xuanzheng.company.dao.impl.CompanyDaoImpl;
import com.xuanzheng.company.dao.impl.CompanyEmployeeDaoImpl;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.entity.CompanyEmployee;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.util.IdGenerator;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

public class CompanyServiceImpl implements CompanyService {
    private final CompanyDao companyDao;
    private final CompanyEmployeeDao companyEmployeeDao;
    
    public CompanyServiceImpl() {
        this.companyDao = new CompanyDaoImpl();
        this.companyEmployeeDao = new CompanyEmployeeDaoImpl();
    }

    @Override
    public String createCompany(Company company) {
        // 检查统一社会信用代码是否已存在
        Company existingCompany = companyDao.getCompanyByCreditCode(company.getCreditCode());
        if (existingCompany != null) {
            return null;
        }
        
        // 设置默认值
        company.setEmployeeCount(0);
        company.setStatus(1); // 正常状态
        
        boolean success = companyDao.addCompany(company);
        if (success) {
            return company.getId();
        }
        return null;
    }

    @Override
    public Company getCompanyById(String id) {
        return companyDao.getCompanyById(id);
    }

    @Override
    public Company getCompanyByCreditCode(String creditCode) {
        return companyDao.getCompanyByCreditCode(creditCode);
    }

    @Override
    public Company getCompanyByManagerId(String managerId) {
        return companyDao.getCompanyByManagerId(managerId);
    }

    @Override
    public boolean updateEmployeeCount(String companyId, int increment) {
        return companyDao.updateEmployeeCount(companyId, increment);
    }

    @Override
    public List<Company> getAllCompanies() {
        return companyDao.getAllCompanies();
    }

    @Override
    public String getNextEmployeeNumber(String companyId) {
        return companyDao.getNextEmployeeNumber(companyId);
    }

    @Override
    public boolean updateCompanyStatus(String id, int status) {
        return companyDao.updateCompanyStatus(id, status);
    }

    @Override
    public String createCompanyFromApproval(User user) {
        // 检查用户是否是公司负责人
        if (user.getRole() != 1) {
            return null;
        }
        
        // 检查公司名称和信用代码是否存在
        if (user.getCompanyName() == null || user.getCompanyCreditCode() == null) {
            return null;
        }
        
        // 创建公司对象
        Company company = new Company();
        company.setName(user.getCompanyName());
        company.setAddress(user.getCompanyAddress());
        company.setPhone(user.getCompanyPhone());
        company.setCreditCode(user.getCompanyCreditCode());
        company.setManagerId(user.getId());
        company.setEmployeeCount(1); // 包含负责人自己
        company.setStatus(1); // 正常状态
        
        boolean success = companyDao.addCompany(company);
        
        if (success) {
            // 更新用户的公司ID和员工编号
            // 公司负责人的员工编号为00000
            Connection conn = null;
            PreparedStatement pstmt = null;
            
            try {
                conn = com.xuanzheng.company.util.DBUtil.getConnection();
                String sql = "UPDATE user SET company_id = ?, employee_number = ? WHERE id = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, company.getId());
                pstmt.setString(2, "00000");
                pstmt.setString(3, user.getId());
                pstmt.executeUpdate();
                
                // 将公司负责人添加到company_employee表
                CompanyEmployee companyEmployee = new CompanyEmployee();
                companyEmployee.setId(user.getId()); // 使用用户ID作为记录ID
                companyEmployee.setCompanyId(company.getId());
                companyEmployee.setUserId(user.getId());
                companyEmployee.setEmployeeNumber("00000");
                companyEmployee.setPosition("负责人");
                companyEmployee.setBaseSalary(null);
                companyEmployee.setStatus(1); // 已通过状态
                companyEmployee.setReason("系统自动创建");
                
                // 直接插入数据库
                PreparedStatement pstmt2 = null;
                try {
                    String insertSql = "INSERT INTO company_employee (id, company_id, user_id, employee_number, position, status, reason) " +
                            "VALUES (?, ?, ?, ?, ?, ?, ?)";
                    pstmt2 = conn.prepareStatement(insertSql);
                    pstmt2.setString(1, companyEmployee.getId());
                    pstmt2.setString(2, companyEmployee.getCompanyId());
                    pstmt2.setString(3, companyEmployee.getUserId());
                    pstmt2.setString(4, companyEmployee.getEmployeeNumber());
                    pstmt2.setString(5, companyEmployee.getPosition());
                    pstmt2.setInt(6, companyEmployee.getStatus());
                    pstmt2.setString(7, companyEmployee.getReason());
                    pstmt2.executeUpdate();
                } finally {
                    if (pstmt2 != null) {
                        pstmt2.close();
                    }
                }
                
            } catch (SQLException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (pstmt != null) {
                    try {
                        pstmt.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
            
            return company.getId();
        }
        
        return null;
    }
} 